package club.dmyang.controller;

import club.dmyang.common.constants.Constants;
import club.dmyang.common.util.QiNiuUploadUtil;
import club.dmyang.common.vo.ArticleVo;
import club.dmyang.common.vo.EditorMdImgResp;
import club.dmyang.common.vo.ResposeVo;
import club.dmyang.entity.Article;
import club.dmyang.entity.ArticleWithBLOBs;
import club.dmyang.entity.Category;
import club.dmyang.entity.Tag;
import club.dmyang.service.ArticleService;
import club.dmyang.service.CategoryService;
import club.dmyang.service.TagService;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by brss on 2018/7/15.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    public static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    private ArticleService articleService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagService tagService;

    /**
     * 发表文章
     * @param article
     * @param contentHtml
     * @param tags
     * @return
     */
    @RequestMapping("/publish")
    @ResponseBody
    public String publish(ArticleWithBLOBs article,
                          @RequestParam("article-content-html-code") String contentHtml,
                          String tags){
        //富文本编辑器上传的name就是article-content-html-code，不会改，只能这里手动了
        article.setContentHtml(contentHtml);
        //System.out.println(article);
        //补全Article对象的内容
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setHits(0);
        article.setVotes(0);
        //把String类型的标签封装成List<Tag>类型
        ArrayList<Tag> tagList = new ArrayList<>();
        if ( tags != null && !tags.equals("") ){
            String[] split = tags.split(",");
            for ( String s : split ){
                Tag t = new Tag();
                t.setTname(s);
                tagList.add(t);
            }
        }
        //调用Service层
        articleService.publishOneArticle(article,tagList);
        return "发表文章成功！";
    }

    /**
     * 修改文章
     * @param article
     * @param contentHtml
     * @param tags
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(ArticleWithBLOBs article,
                         @RequestParam("article-content-html-code") String contentHtml,
                         String tags){
        //富文本编辑器上传的name就是article-content-html-code，不会改，只能这里手动了
        article.setContentHtml(contentHtml);
        //补全Article对象的内容
        article.setUpdateTime(new Date());
        //把String类型的标签封装成List<Tag>类型
        ArrayList<Tag> tagList = new ArrayList<>();
        if ( tags != null && !tags.equals("") ){
            String[] split = tags.split(",");
            for ( String s : split ){
                Tag t = new Tag();
                t.setTname(s);
                tagList.add(t);
            }
        }
        //调用Service层
        articleService.updateOneArticle(article,tagList);
        return "修改文章成功！";
    }

    @ResponseBody
    @RequestMapping("/delete/{aid}")
    public String deleteOneArticle(@PathVariable("aid") Integer aid) {
        articleService.delOneArticle(aid);
        return "删除文章成功！";
    }

    /**
     * 上传图片文件到七牛云，并返回响应接口
     * @param request
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
    public EditorMdImgResp uploadImg(HttpServletRequest request, @RequestParam("editormd-image-file") MultipartFile file){
        String filename = "";
        try {
            filename = QiNiuUploadUtil.uploadInputStream(file.getInputStream());
        } catch (IOException e) {
            LOGGER.error("上传文件失败！文件名："+file.getName());
            e.printStackTrace();
        }
        //String url = Constants.QINIU_IMG_BUCKET_URL + "/articleimgs/" + filename;
        String url = Constants.QINIU_IMG_BUCKET_URL + "/" + filename;
        EditorMdImgResp editorMdImgResp = new EditorMdImgResp(url);
        return editorMdImgResp;
    }

    /**
     * 分页列出文章列表
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResposeVo listArticleByPageAndLimit(Integer page,Integer limit){

        //查询出文章列表
        List<Article> articleList = articleService.findArticlesByPageAndLimit(page, limit);
        //用于返回前端的List
        List<ArticleVo> articleVoList = new ArrayList<>();
        //查询每篇文章的分类
        for (Article a : articleList) {
            Category c = categoryService.findOneById(a.getCategoryId());
            ArticleVo articleVo = new ArticleVo();
            //装入数据
            try {
                BeanUtils.copyProperties(articleVo,a);
                articleVo.setCategory(c.getCname());//装入分类的名字
            } catch (Exception e) {
                e.printStackTrace();
            }
            articleVoList.add(articleVo);
        }
        //数据库中一共有多少篇文章
        int count = articleService.findAllNums();
        return new ResposeVo(0,"成功",count,articleVoList);
    }

    /**
     * 根据文章id，跳转到编辑文章页面，用原来文章信息填充页面中内容
     * @param aid
     * @param model
     * @return
     */
    @RequestMapping("/edit/{aid}")
    public String edit(@PathVariable("aid") Integer aid, Model model){
        //查找这篇文章
        ArticleWithBLOBs article = articleService.findOneArticle(aid);
        model.addAttribute("article",article);
        //查找这篇文章对应的标签
        List<Tag> tagList = tagService.findByArticleId(aid);
        //把List拼接成符合前端要求的字符串
        String tags = "";
        for (Tag t : tagList){
            tags += t.getTname() + ",";
        }
        if (tags.length()>0){
            //去除多余逗号
            tags = tags.substring(0,tags.length()-1);
        }
        model.addAttribute("tags",tags);
        //查找所有分类，供选择
        List<Category> categoryList = categoryService.findAll();
        model.addAttribute("categoryList",categoryList);
        return "admin/article-write";
    }

}
